// pages/goods/index.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
      price:10,
      number:1,
      buy_success : !1,//支付成功
      user_nickname : '',
      user_iphone : '',
      region:['北京'],
      items: [
        { name: 'pay', value: '余额支付', isshow:!0 ,checked: 'true'},
        { name: 'alipay', value: '支付宝支付' ,isshow:!1},
        { name: 'wxpay', value: '微信支付' ,isshow:!1}
      ],
      planterNickname: ['无'],
      planterIphone: ['无'],
      planterIndex : 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var treeid = options.id;
    this.getTreeMessage(treeid);
    this.getBalance();
    this.setData({
      userid: wx.BaaS.storage.get('userId'),
      treeid: treeid
    })
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function (e) {
      
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  test:function(){
    this.saveOrder();
  },
  bindPlanterMsg: function(e){//选择植树人
    this.setData({
      planterIndex: parseInt(e.detail.value)
    })
  },
  sure:function(){//确定订单
    this.setData({
      hidden: !1,
      buy_success: !0
    })
    
  },
  cancel:function(){//窗口关闭
    this.setData({
      hidden:!1
    })
  },
  sure_order:function(){//订单完成
    this.setData({
      buy_success: !1
    });
    this.updataBalance();
  },
  bindRegionChange:function(e){//选择地区
    let region = e.detail.value;
    var t = this;
    var url = app.getUrl() + '/planttingTree/order';
    var data  =  {
      type: 'getPlanter',
      province: region[0],
      city: region[1],
      area: region[2],
      treeid: this.data.treeid
    };
    app.core(url,'GET',data,function(res){
      var planterId = [];
      var planterNickname = [];
      var planterIphone = [];
      [].forEach.call(res.data, function (value) {
        planterId.push(value.memberid);
        planterNickname.push(value.realname);
        planterIphone.push(value.phone);
      });
      t.setData({
        planterId: planterId.length > 0 ? planterId : ['无'],
        planterNickname: planterNickname.length > 0 ? planterNickname : ['无'],
        planterIphone: planterIphone.length > 0 ? planterIphone : ['无'],
        region: region
      })
    })
  },
  numberAdd:function(){//数量+
    this.priceChange('add');
  },
  numberReduce:function(){//数量-
    this.priceChange('reduce');
  },
  getValue: function(e){//获取用户填写的数据 主要为nickname和phone两种
    let type = e.target.dataset.type;//获取
    let value = e.detail.value;
    let t = this;
    if(type === 'user_nickname'){
      t.setData({
        user_nickname: value
      })
    } else if (type === 'user_iphone'){
      t.setData({
        user_iphone: value
      })
    }else{
      t.setData({
        remark: value
      })
    }
  },
  priceChange:function(type){
    var number = this.data.number;
    if (number === 1 && type ==='reduce'){
      return;
    }
    var operation = (type === 'add') ? 1 : -1;
    this.setData({
      number: number + operation
    })
  },
  getTreeMessage: function(id){//获取树的详细
    var t = this;
    var url = app.getUrl() + '/planttingTree/tree';
    var data = {
      id: id,
      type: 'getTree',
      memberid: wx.BaaS.storage.get('userId')
    }
    app.core(url, 'GET', data, function (res) {
      t.setData({
         price:res.data.price
      })
    })
  },
  saveOrder: function(){
    let orderno = 'TREE';//订单编号前的标识 随便加的 
    var data = this.data;
    if (!this.data.planterId || this.data.planterId[0] === '无'){
      app.showLog('当前未选择联系人')
      return;
    }
    if(!this.data.canBuy){
      app.showLog('余额不足');
      return  false;
    }
    if (!this.ckeckInput(this.data.user_nickname)){
      app.showLog('联系人不能为空');
      return false;
    }
    if (!this.ckeckInput(this.data.user_iphone)){
      app.showLog('手机号不能为空');
      return false;
    }
    if (!app.checkInput('phone', this.data.user_iphone)){
      app.showLog('手机号格式不正确');
      return false;
    }
    var url = app.getUrl() + '/planttingTree/order';
    var postData = {
      type: 'saveOrder',
      memberid: data.userid,
      serial_number: orderno + (new Date().getTime()),
      status: '1',
      payment_method: '1',//订单支付方式（1为余额支付）
      total_cost: data.price,
      goodprice: data.price/data.number,
      address: data.region.join(''),
      remark: data.remark,
      nickname: data.user_nickname,
      planterid: data.planterId[data.planterIndex],
      phone: parseInt(data.user_iphone),
      treeid:data.treeid
    }
    app.core(url, 'POST', postData,function(res){
      if(res.data.code === -1){
        app.showLog(res.data.msg);
      }else{
        if(res.data == 404){
          app.showLog('未知错误');
        }else{
          app.showLog('支付成功');
          setTimeout(function(){
            wx.navigateTo({    //保留当前页面，跳转到应用内的某个页面（最多打开5个页面，之后按钮就没有响应的）
              url: '/pages/order/index'
            })
          },1000)
        }
      }
    })
  },
  ckeckInput: function(value){
    if(!this.empty(value)){
      return false;
    }else{
      return true;
    }
  },
  empty: function(str){//是否为空（判断是否有输入内容
    str = str.replace(/\s+/g, ""); //去除空格
    if (str === "" || str === undefined || str.length<=0){
      return false
    };
    return true;
  },
  getBalance: function(){
    var t = this;
    var url = app.getUrl() + '/planttingTree/member';
    var data = {
      type: 'getmember',
      wxuserid: wx.BaaS.storage.get('userId')
    }
    app.core(url, 'GET', data, function (res) {
      var balance = res.data.balance;
      var canBuy = !0;
      if (balance < t.data.price){
        canBuy = !1;
      }
      t.setData({
        balance: balance,
        canBuy: canBuy,
        id: res.data.id
      })
    })
  }
})